﻿using Abp.AspNetCore.Mvc.Authorization;
using Abp.AspNetCore.Mvc.Controllers;
using Abp.Runtime.Security;
using Abp.UI;
using Admin.Services;
using Admin.Services.Dto.Users;
using Admin.ViewModels.User;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Web.Models;

namespace Admin.Controllers
{
    [AbpMvcAuthorize]
    public class UserController : AbpController
    {
        private readonly UserAppService _userAppService;

        public UserController(UserAppService accountAppService)
        {
            _userAppService = accountAppService;
        }

        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }


        [HttpPost]
        [AllowAnonymous]
        public async Task<JsonResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResponse(false) { Error = new ErrorInfo(0, "验证失败！") });
            }
            var input = new LoginInput { Name = model.Name, Password = model.Password };
            var output = _userAppService.Login(input);
            if (output.User == null)
            {
                throw new UserFriendlyException("登录失败");
            }
            var claims = new List<Claim>
            {
                new Claim(AbpClaimTypes.UserId, output.User.Id.ToString()),
                new Claim(AbpClaimTypes.UserName, output.User.Name)
            };
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties { IsPersistent = model.RememberMe };
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            if (string.IsNullOrEmpty(returnUrl))
            {
                return Json(new AjaxResponse() { TargetUrl = Url.Action("Index", "Home") });
            }
            return Json(new AjaxResponse() { TargetUrl = returnUrl });



        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login");
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public JsonResult Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResponse(false) { Error = new ErrorInfo(0, "验证失败") });
            }
            var input = new RegisterInput()
            {
                Name = model.Name,
                Password = model.Password,
            };
            var output = _userAppService.Register(input);
            if (output.User == null)
            {
                throw new UserFriendlyException("注册失败");
            }

            return Json(new AjaxResponse(true) { TargetUrl = Url.Action("Login") });
        }
    }
}